<template>
  <div class="layui-container fly-marginTop">
  <div class="fly-panel fly-panel-user" pad20>
    <div class="layui-tab layui-tab-brief" lay-filter="user">
      <ul class="layui-tab-title">
        <li><a href="login.html">登入</a></li>
        <li class="layui-this">注册</li>
      </ul>
      <div class="layui-form layui-tab-content" id="LAY_ucm" style="padding: 20px 0;">
        <div class="layui-tab-item layui-show">
          <div class="layui-form layui-form-pane">
            <form action=""  @submit.prevent="onSubmit" method="post">
              <div class="layui-form-item">
                <label for="L_email" class="layui-form-label">邮箱</label>
                <div class="layui-input-inline">
                  <input type="text" id="user_mail" v-model="regForm.email" name="email" required lay-verify="required|email" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-mid layui-word-aux">将会成为您唯一的登入名</div>
              </div>

              <div class="layui-form-item">
                <label for="L_vercode" class="layui-form-label">验证码</label>
                <div class="layui-input-inline">
                   <input type="text" id="L_vercode" v-model="regForm.vercode" name="vercode" required="" lay-verify="required" placeholder="请输入邮箱验证码" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-mid" style="padding: 0!important;">
                  <button type="button" class="layui-btn layui-btn-normal get_mail_code_btn" :disabled="isDisabled" @click="sendEmail" id="mail_getvercode">{{buttonName}}</button>
                </div>
              </div>
              <div class="layui-form-item">
                <label for="L_username" class="layui-form-label">昵称</label>
                <div class="layui-input-inline">
                  <input type="text" id="L_username"  v-model="regForm.username" name="username" required lay-verify="required|username" autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-form-item">
                <label for="L_pass" class="layui-form-label">密码</label>
                <div class="layui-input-inline">
                  <input type="password" id="L_pass" v-model="regForm.pass" name="pass" required lay-verify="pass" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-mid layui-word-aux">6到12个字符</div>
              </div>
              <div class="layui-form-item">
                <label for="L_repass" class="layui-form-label">确认密码</label>
                <div class="layui-input-inline">
                  <input type="password" id="L_repass" v-model="regForm.repass" name="repass" required lay-verify="required" autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-form-item">
                <label for="L_vercode" class="layui-form-label">图形验证</label>
                <div class="layui-input-inline">
                  <input type="text" id="L_verify" v-model="regForm.img_code" name="img_code" required lay-verify="required" placeholder="请输入图形验证码" autocomplete="off" class="layui-input">
                </div>
                <!-- <div class="layui-form-mid">
                  <img id="verify_img" src="{:captcha_src()}" alt="验证码" onclick="refreshVerify()" style="height: 38px;margin-top: -6px;">
                </div> -->
                <div class="layui-form-mid">
                  <img id="verify_img" :src="host+'/micro-bbs/v2/captcha/image/'+captcha_id" alt="验证码" @click="refreshVerify" style="height: 38px;margin-top: -6px;">
                </div>
              </div>
              <div class="layui-form-item">
                <button class="layui-btn" lay-filter="*" lay-submit>立即注册</button>
              </div>
              <div class="layui-form-item fly-form-app">
                <span>或者直接使用社交账号快捷注册</span>
                <a href="{:url('api/index/qqlogin')}" onclick="layer.msg('正在通过QQ登入', {icon:16, shade: 0.1, time:0})" class="iconfont icon-qq" title="QQ登入"></a>
                <a href="{:url('api/index/sinalogin')}" onclick="layer.msg('正在通过微博登入', {icon:16, shade: 0.1, time:0})" class="iconfont icon-weibo" title="微博登入"></a>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>
</template>
<script>
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
export default {
   components: {
  },
  inject:['store'],
  name: "MyRegister",
  props: ["register"],
  data() {
    return {
      regForm: {
          email: '',
          vercode: null,
          username: '',
          pass: '',
          repass: '',
          img_code: '',
      },
      buttonName: "获取验证码",
			isDisabled: false,
			time: 60,
      captcha_id: "",
      host: "http://127.0.0.1:8080"
    };
  },
  watch: {
    // 监听父组件传过来的register变量，设置this.isRegister的值
    register: function(val) {
      if (val) {
        this.isRegister = val;
      }
    },
    // 监听this.isRegister变量的值，更新父组件register变量的值
    isRegister: function(val) {
      if (!val) {
        this.$refs["ruleForm"].resetFields();
        this.$emit("fromChild", val);
      }
    }
  },
  mounted(){
    this.refreshVerify()
  },
  methods: {
    onSubmit() {
      console.log("方法进来了")
      let next = true
      //效验两次密码
      if(this.regForm.pass != this.regForm.repass){
        ElMessage({
            message: '两次密码不一致!',
            type: 'error',
            offset: 200,
        })
        return false;
      }
      //效验全部通过提交注册
      if(next===true){
        this.Register()
      }
    },
    Register() {
      this.regForm.captcha_id = this.captcha_id
      this.regForm.vercode = parseInt(this.regForm.vercode)
      request.post('/micro-bbs/v1/user/register', this.regForm).then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
          console.log("data:",data)
           ElMessage({
              message: "恭喜你，注册成功！",
              type: 'success',
              offset: 200,
          })
          this.$router.push("/")
        }else{
           ElMessage({
              message: msg,
              type: 'error',
              offset: 200,
          })
          this.refreshVerify()
        }
      })
      
    },
    //获取验证码
    refreshVerify() {
      const params = {
        params: {
        }
      }
      request.get('/micro-bbs/v2/captcha/generate', params).then((res) => {
        const { code, data } = res
        if (code === 200) {
          this.captcha_id = data.id
        }
      })
    },
    //发送邮箱
    sendEmail() {
      let emailBool = this.checkEmail()
      if(emailBool){
        const params = {
          params: {
            email: this.regForm.email,
          }
        }
        request.get('/micro-bbs/v2/email/sendCode', params).then((res) => {
          console.log("res:",res)
          const { code, data } = res
          if (code === 200) {
            console.log("data:",data)
            this.timestart()
          }
        })
      }
    },
    //倒计时
    timestart() {
      let me = this;
      me.isDisabled = true;
      let interval = window.setInterval(function() {
        me.buttonName = '（' + me.time + '秒）后重发';
        --me.time;
        if(me.time < 0) {
          me.buttonName = "重新发送";
          me.time = 60;
          me.isDisabled = false;
          window.clearInterval(interval);
        }
      }, 1000);
    },
    //效验邮箱
    checkEmail(){
      if(this.regForm.email==""){
        ElMessage({
            message: '邮箱不能为空!',
            type: 'error',
            offset: 200,
        })
        return false
      }
      var reg=/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
      if(!reg.test(this.regForm.email) ){
        ElMessage({
            message: '邮箱格式错误!',
            type: 'error',
            offset: 200,
        })
        return false
      }
      return true
    }
  }
};
</script>